#include "DFM.h"


// *************************************
// DFM functions
// *************************************


uint32_t DFM::GetID()
{
    return li.GetID();
}


void DFM::Reset()
{
    int channel;
    
    // Hint: with the current FPGA revision (2) we have to 
    // set the reaction time after each reset.
    // We also set the limits again (just to be sure).
    for (channel = 0; channel < 8; channel ++) {
        li.SetShortAddress(1, channel);
        li.WriteWord(0);
    }
    li.Reset();
    for (channel = 0; channel < 8; channel ++) {
        li.SetShortAddress(2, channel);
        li.WriteWord(delay[channel]);
        li.SetShortAddress(1, channel);
        li.WriteWord(limit[channel]);
    }
}


void DFM::SetLimit(uint8_t channel, uint16_t newlimit)
{
    limit[channel] = newlimit;
    li.SetShortAddress(1, channel);
    li.WriteWord(newlimit);
}


uint16_t DFM::GetLimit(uint8_t channel)
{
    li.SetShortAddress(1, channel);
    return li.ReadWord();
}


void DFM::SetFlowLimit(uint8_t channel, double newlimit)
{
    SetLimit(channel, Pulses(channel, newlimit));
}


double DFM::GetFlowLimit(uint8_t channel)
{
    return Flow(channel, GetLimit(channel));
}


uint16_t DFM::GetRate(uint8_t channel)
{
    li.SetShortAddress(0, channel);
    return li.ReadWord();
}


double DFM::GetFlow(uint8_t channel)
{
    return Flow(channel, GetRate(channel));
}


void DFM::SetReactionTime(uint8_t channel, uint16_t time)
{
    delay[channel] = time;
    li.SetShortAddress(2, channel);
    li.WriteWord(time);
}


void DFM::SetReactionTime(uint16_t time)
{
    for (int channel = 0; channel < 8; channel ++)
        SetReactionTime(channel, time);
}


uint8_t DFM::GetState()
{
    li.SetShortAddress(2, 0);
    return li.ReadByte();
}


bool DFM::GetState(uint8_t channel)
{
    return ((GetState() >> (8 - (channel+1))) & 1) == 1;
}


void DFM::SetPulses(double ipulses)
{
    for (int channel = 0; channel < 8; channel ++)
        SetPulses(channel, ipulses);
}


void DFM::SetPulses(uint8_t channel, double ipulses)
{
	pulses[channel] = ipulses / 60.;
}


double DFM::GetPulses(uint8_t channel)
{
	return pulses[channel] * 60.;
}
